<?php

namespace App\Console\Commands\Fee;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Library\FeiShu\SendFs;
use App\Library\Rms\RmsShopApi;
use App\Models\Fee\FeeAnnualOrderModel;
use App\Models\Guanyuan\GuanyuanSyncShopListModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\StartBusiness\OpenShopStartBusinessModel;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Kuafu\GeneralFs\BuildFs;

class CheckoutShopFee extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fee:checkout-shop-fee';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检查年费订单生成情况';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 判断是正常营业但是startFeeTime<=0的
        $shopIds = OpenShopMainProcessModel::query()
            ->where('shopId', '>', 0)
            ->whereIn('orderNo', function ($q) {
                $q->select('orderNo')
                    ->from((new OpenShopSignOrderModel())->getTable())
                    ->whereIn('shopCode', function ($qq) {
                        $qq->select('code')
                            ->from((new GuanyuanSyncShopListModel())->getTable())
                            ->where('openBusinessDate', '!=', '')
                            ->where('status', '正常营业');
                    });
            })
            ->where('startFeeTime', '<=', 0)
            ->pluck('shopId')
            ->toArray();

        // 如果存在发送消息通知
        if (count($shopIds)) {
            // 获得门店信息
            $shopInfo = (new RmsShopApi())->getShopByIds($shopIds, ['id', 'shopCode', 'name'])['data']['shopList'] ?? [];
            $shopInfo = collect($shopInfo)->keyBy('id')->toArray();

            // 组数据
            $errorShopMsg = '';

            foreach ($shopIds as $shopId) {

                // 过滤测试门店-不存在跳过
                if (!isset($shopInfo[$shopId]['shopCode'])) {
                    continue;
                }

                // 过滤测试门店-不满足跳过
                if ($shopInfo[$shopId]['shopCode'] >= OpenShopSignOrderModel::SHOP_CODE_TEST || $shopInfo[$shopId]['shopCode'] <= 0) {
                    continue;
                }

                // 尝试获取年费收取时间
                $startFeeTime = InitFeeDate::getStartFeeTime(0, $shopId);
                if ($startFeeTime == 0) {

                    // 获取门店首次收银时间
                    $firstDateByBusiness = GuanyuanSyncShopListModel::query()->where('code', $shopInfo[$shopId]['shopCode'])->first();

                    if (null != $firstDateByBusiness && strlen($firstDateByBusiness->earliestRevenueDate)) {
                        $startFeeTime = Carbon::parse($firstDateByBusiness->earliestRevenueDate)->format('Ymd');
                    }

                    if ($startFeeTime) {
                        $errorShopMsg .= '门店编号：' . $shopInfo[$shopId]['shopCode'] . ' ' . '门店名称：' . ($shopInfo[$shopId]['name'] ?? '-') . '【已修正-最早收银日期为年费收取开始时间】' .PHP_EOL;
                    } else {
                        $errorShopMsg .= '门店编号：' . $shopInfo[$shopId]['shopCode'] . ' ' . '门店名称：' . ($shopInfo[$shopId]['name'] ?? '-') . PHP_EOL;
                        continue;
                    }
                }

                // 查主单
                $main = OpenShopMainProcessModel::getMainOrder($shopId);
                if (!$main) {
                    continue;
                }
                // 更新年费
                OpenShopMainProcessModel::updateFee($main->orderNo, $startFeeTime, 0);
            }

            if (strlen($errorShopMsg)) {
                BuildFs::newRobot(SendFs::ROBOT_OPEN_SHOP)
                    ->setTitleContent("门店的年费开始计算时间为0", $errorShopMsg)
                    ->when(!isTest(), function ($fs) {
                        $fs->setAtUid('5dd87136') //山治
                           ->setAtUid('9efgbcdb') //吉连
                           ->setAtUid('513296d9'); //彼得潘
                    })
                    ->send();
            }
        }


        $content = '';
        OpenShopStartBusinessModel::query()
            ->where('startBusinessTime', '>', 0)
            ->with(['mainProcessesRel', 'signOrderRel'])
            ->chunk(100, function ($openStarts) use (&$content) {
                foreach ($openStarts as $openStart) {
                    $this->info($openStart->orderNo);
                    // 作废的订单过滤
                    if (optional($openStart->signOrderRel)->status == SignOrderEnum::ORDER_STATUS_NO) {
                        continue;
                    }
                    foreach ($openStart->mainProcessesRel as $mainProcessRel) {

                        // 过滤子单
                        if ($mainProcessRel->childLocationOrder == MainProcessEnum::CHILD_ORDER_1) {
                            continue;
                        }

                        //获得年费开始时间
                        $startFeeTime  = $mainProcessRel->startFeeTime;
                        $calculateTime = $startBusinessTime = $startFeeTime ? Carbon::createFromFormat('Ymd', $startFeeTime)->endOfDay()->timestamp : Carbon::createFromTimestamp($openStart->startBusinessTime)->endOfDay()->timestamp;

                        //门店最近年费过期时间
                        $apartYear = -1;
                        while ($calculateTime <= time()) {
                            ++$apartYear;
                            $calculateTime = Carbon::createFromTimestamp($startBusinessTime)->addYears($apartYear)->endOfDay()->timestamp;
                        }

                        // 获得80天后的时间
                        $nextEndDate = Carbon::now()->addDays(80)->timestamp;

                        // 如果年费的截止时间是小于80天（给10天真空期）的话就要存在年费订单 反之不校验
                        if ($calculateTime > $nextEndDate) {
                            continue;
                        }

                        // 是否有年费订单
                        $feeRes = false;

                        //与年费订单比较
                        FeeAnnualOrderModel::query()
                            ->withoutGlobalScope('isDel')
                            ->where('shopId', $mainProcessRel->shopId)
                            ->with(['changesLogRel'])
                            ->get()
                            ->each(function (FeeAnnualOrderModel $feeAnnualOrderModel) use ($calculateTime, &$feeRes){

                                // 如果延期会调整截止时间  找到原始截止日期
                                $endTime = '';
                                foreach ($feeAnnualOrderModel->changesLogRel as $changeLog) {
                                    if ($changeLog->field == 'endTime') {
                                        $endTime = $changeLog->beforeValue;
                                        break;
                                    }
                                }

                                // 如果没有延期的就拿年费的
                                if (!$endTime) {
                                    $endTime = $feeAnnualOrderModel->endTime;
                                }

                                // 判断是否存在相同结束时间的年费订单
                                if ($endTime == $calculateTime) {
                                    $feeRes = true;
                                }
                            });

                        if (!$feeRes) {
                            $shopInfo = (new RmsShopApi())->getShopByCode($openStart->signOrderRel->shopCode) ?? [];
                            if (isset($shopInfo['code']) && $shopInfo['code'] == 0) {
                                continue;
                            }
                            if ($shopInfo['data']['type'] == RmsShopApi::SHOP_TYPE_DIRECT) {
                                continue;
                            }
                            if ($shopInfo['data']['status'] == RmsShopApi::SHOP_STATUS_OFF) {
                                continue;
                            }
                            $content .= '门店编号：' . $openStart->signOrderRel->shopCode . ' ' . '门店名称：' . ($shopInfo['data']['name'] ?? '-') . PHP_EOL;
                        }
                    }
                }
            });

        if ($content) {
            BuildFs::newRobot(SendFs::ROBOT_OPEN_SHOP)
                  ->setTitleContent("检测到年费未生成门店信息", $content)
                  ->setAtUid('5dd87136') //山治
                  ->setAtUid('9efgbcdb') //吉连
                  ->setAtUid('513296d9') //彼得潘
                  ->send();
        }

    }
}
